#!/bin/env python
import base64
import re
import sys


class SSRNode:
    group = ""
    remarks = ""
    host = ""
    remote_port = ""
    password = ""
    method = ""
    protocol = ""
    protocol_param = ""
    obfs = ""
    obfs_param = ""

    def __init__(self, ssr_str):
        self.parse_ssr_str(ssr_str)
        return

    @classmethod
    def parse_ssr_str(cls, ssr_str):
        parsed = ssr_str_convert_base64_str(ssr_str)
        decode = str(base64.b64decode(parsed), 'utf-8')
        matchObj = re.match(
            r"(.*?):(.*?):(.*?):(.*?):(.*?):(.*?)/\?obfsparam=(.*?)&protoparam=(.*?)&remarks=(.*?)&group=(.*?)$", decode)

        if matchObj:
            cls.host = matchObj.group(1)
            cls.remote_port = matchObj.group(2)
            cls.protocol = matchObj.group(3)
            cls.method = matchObj.group(4)
            cls.obfs = matchObj.group(5)
            cls.password = matchObj.group(6)
            cls.obfs_param = str_base64_decode(matchObj.group(7))
            cls.protocol_param = str_base64_decode(matchObj.group(8))
            cls.remarks = str_base64_decode(matchObj.group(9))
            cls.group = str_base64_decode(matchObj.group(10))
        return


def convert_base64_str(cstr):
    cstr = cstr.replace("-", "+", -1).replace("_", "/", -1)
    padding = len(cstr) % 4
    for _ in range(padding):
        cstr += '='
    return cstr


def ssr_str_convert_base64_str(ssr_str):
    ssr_str = ssr_str.lstrip('ssr://')
    return convert_base64_str(ssr_str)


def str_base64_decode(cstr):
    d = base64.b64decode(convert_base64_str(cstr))
    return str(d, 'utf-8')


def main():
    ssr_str = sys.argv[1]

    ssrNode = SSRNode(ssr_str)
    print(ssrNode.protocol_param)


if __name__ == "__main__":
    main()
